import random
import string
from typing import Sequence, Mapping, Union
from datetime import datetime

from scipy import signal
from .file import *
from .decorator import *
from .report import *

def join_vars(*_vars, sep:str='_', non_null=False):
    '''拼接变量'''
    if non_null:
        return sep.join([str(v) for v in _vars if v])
    return sep.join([str(v) for v in _vars])

def to_percent(num:float):
    '''数字转百分比'''
    # assert not isinstance(num, np.ndarray)
    return str(round(num*100)) + '%'

def check_param(*groups:Tuple[Any, Sequence[Any]]):
    '''检查参数'''
    for param, scope in groups:
        if param not in scope:
            raise ValueError(f'Unsupported param by {param}, not in {scope}')

def custom_selection(selections:List[Any], return_index:bool=False) -> Any:
    '''自定义配置'''
    for i, search in enumerate(selections):
        print(f'{i} {search}')
    print(f'q quit')
    choice = input('Select index > ')
    if choice == 'q':
        exit()
    if not choice: choice = 0  # 默认选择第一个
    index = int(choice)
    if return_index:
        return selections[index], index
    return selections[index]

def generate_time_id(_time:datetime=None, msec:bool=False, split:bool=False, 
                     convert:Optional[Union[Sequence[bool], Mapping[str, bool]]]=None):
    '''生成时间id'''
    _time = _time or datetime.now()
    formats = {  
        (True, True): '%Y-%m-%d %H:%M:%S.%f',
        (True, False): '%Y%m%d%H%M%S%f',
        (False, True): '%Y-%m-%d %H:%M:%S',
        (False, False): '%Y%m%d%H%M%S'
    }
    _format = formats[(msec, split)]
    if isinstance(_time, str):
        _time = datetime.strptime(_time, _format)
        if isinstance(convert, Sequence):
            return generate_time_id(_time, *convert)
        elif isinstance(convert, dict):
            return generate_time_id(_time, **convert)
    elif isinstance(_time, datetime):
        _time = _time.strftime(_format)
        if msec:_time = _time[:-3]  # 移除毫秒部分
    else:
        raise ValueError(f'Not support type of {type(_time)}')
    return _time

def generate_letter_id(n:int=3):
    '''生成英文字母id'''
    return ''.join(random.sample(string.ascii_letters, n))
